//
//  StatusListViewModel.swift
//  sinaweibo
//
//  Created by mac on 15/11/16.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class StatusListViewModel: NSObject {
    
    class func loadData(finished: (array: [Status]?) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        let parameters = ["access_token": token]
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                finished(array: nil)
                return
            }
            
            if let array = result!["statuses"] as? [[String : AnyObject]] {
                
                var list = [Status]()
                for item in array {
                    
                    let s = Status(dict: item)
                    
                    list.append(s)
                }
//                finished(array: list)
                //完成单张图片的缓存
                StatusListViewModel.cacheStatusImage(list, finished: finished)
            }
        }
    }
    
    private class func cacheStatusImage(array:[Status],finished: (array: [Status]?) -> ()) {
        //缓存单张图片
        if array.count == 0{
            return
        }
        
        //创建群组
        let group = dispatch_group_create()
        
        for s in array {
        
            if let imageUrls = s.imageURLs{
            
                if imageUrls.count != 1 {
                
                    continue
                }
                
                for url in imageUrls{
                    //开始下载单张图片
                    //异步加载图片的开始
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        print("单张图片下载完成")
                        //异步任务离开数组
                        dispatch_group_leave(group)
                    })
                }
            }
        }
     
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //在主线程完成回调
            print("所有的图片都已经下载完成")
            finished(array: array)
        }
        
    }
    
    
    
}

